﻿namespace PhoneUtils.View
{
    using System;
    using System.Net;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Documents;
    using System.Windows.Ink;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Animation;
    using System.Windows.Shapes;
    using Microsoft.Phone.Controls;
    using PhoneUtils.ViewModel;

    /// <summary>
    /// This <see cref="PhoneApplicationPage"/> invokes the appropriate events on the datacontext if it is an <see cref="INavigationAware"/>.
    /// </summary>
    public class NavigationAwarePage : PhoneApplicationPage
    {
        /// <summary>
        /// Called when a page is no longer the active page in a frame.
        /// </summary>
        /// <param name="e">An object that contains the event data.</param>
        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            this.InvokeIfNavigationAware(na => na.OnNavigatedFrom(e, this.NavigationContext));
        }

        /// <summary>
        /// Called when a page becomes the active page in a frame.
        /// </summary>
        /// <param name="e">An object that contains the event data.</param>
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            this.InvokeIfNavigationAware(na => na.OnNavigatedTo(e, this.NavigationContext));
        }

        /// <summary>
        /// Called just before a page is no longer the active page in a frame.
        /// </summary>
        /// <param name="e">An object that contains the event data.</param>
        protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            base.OnNavigatingFrom(e);
            this.InvokeIfNavigationAware(na => na.OnNavigatingFrom(e, this.NavigationContext));
        }

        /// <summary>
        /// Called when navigating to a fragment on a page.
        /// </summary>
        /// <param name="e">An object that contains the event data.</param>
        protected override void OnFragmentNavigation(System.Windows.Navigation.FragmentNavigationEventArgs e)
        {
            base.OnFragmentNavigation(e);
            this.InvokeIfNavigationAware(na => na.OnFragmentNavigation(e, this.NavigationContext));
        }

        /// <summary>
        /// Invokes the given action if the datacontext is navigation aware.
        /// </summary>
        /// <param name="action">The action to invoke.</param>
        private void InvokeIfNavigationAware(Action<INavigationAware> action)
        {
            var context = this.DataContext as INavigationAware;
            if (context != null)
            {
                action(context);
            }
        }
    }
}
